let util = require('../../../../common/util/util.js')
let text = require('../../../../common/util/text.js')
const app = getApp()

const xAudio = wx.createInnerAudioContext({
    obeyMuteSwitch: false,
    success: function (res) {
        console.log(res)
        console.log("开启静音模式下播放音乐的功能");
    },
    fail: function (err) {
        console.log(err)
        console.log("静音设置失败");
    },
});
/* 背景音乐 */
const xBackMusic = wx.getBackgroundAudioManager();
Page({
  data: {
    week:'',
    treatment_item_id:'',
    action_list:[],
    type:'',
    current:-1,
    count:0,
    class:1,
    PracticeStatus:false,
    showtips:false
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      let that =this;
      that.setData({
        week:Number(options.week),
        treatment_item_id:options.treatment_item_id,
        type:Number(options.type)
      })
      that.xInit()
  },
  /**
   *   监听页面初次渲染完成
   */
  onReady() {
    xBackMusic.src='1'
  },
  /**
   * 生命周期函数--监听页面显示
   */
  xChildReload: function () {
    var pages = getCurrentPages();//当前页面栈
    if (pages.length > 1) {
      var beforePage = pages[pages.length - 2];//获取上一个页面实例对象
       beforePage.xInfo();//触发父页面中的方法
    }
  },
  // 音频播放
  xToplay:function(e){
    let that = this
    let params = e.currentTarget.dataset
    let index = e.currentTarget.dataset.index
    if(xBackMusic.src!=e.currentTarget.dataset.file){
      xAudio.src = e.currentTarget.dataset.file
      xBackMusic.src = e.currentTarget.dataset.file
      xBackMusic.title = e.currentTarget.dataset.name
      if(that.data.current){
        for(let index in that.data.action_list){
          for(let i in that.data.action_list[index].data){
            if(that.data.action_list[index].data[i]._id == that.data.current){
              that.setData({
                [`action_list[${index}].data[${i}].play`]:false
              })
            }
          }
        }
      }
    }
    that.setData({
      current:params.id,
      [`action_list[${index}].data[${params.i}].play`]:true
    })
    that.xAudioPlay(index,params.i)
  },
  // 音频暂停
  xTostop:function(e){
    let params = e.currentTarget.dataset
    this.setData({
      [`action_list[${params.index}].data[${params.i}].play`]:false
    })
    this.xAudioStop()
  },
  xAudioPlay: function (index,i) {
    let that = this
    xBackMusic.play()
    var index =index;
    // setTimeout(() => {
        xBackMusic.currentTime
        xBackMusic.onTimeUpdate(() => {
            let xNowTime = xBackMusic.duration - xBackMusic.currentTime
            let time = that.formatSeconds(xNowTime)
            that.setData({
              [`action_list[${index}].data[${i}].countdown`]:time
            })
        })
        xBackMusic.onEnded(()=>{
           that.setData({
             current:-1,
             [`action_list[${index}].data[${i}].countdown`]:that.data.action_list[index].data[i].playback_duration,
             [`action_list[${index}].data[${i}].play`]:false,
           })
           that.xToadd()
        })
    // }, 1000)
},
formatSeconds(value) {
    var theTime = parseInt(value);// 秒
    var middle= 0;// 分
    var hour= 0;// 小时
    if(theTime > 60) {undefined
        middle= parseInt(theTime/60);
        theTime = parseInt(theTime%60);
        if(middle> 60) {undefined
            hour= parseInt(middle/60);
            middle= parseInt(middle%60);
        }
    }
    let h = parseInt(hour) > 0 ? parseInt(hour) + ":"  : ''
    let m = parseInt(middle) > 9 ? parseInt(middle) : '0' + parseInt(middle)
    let s = parseInt(theTime) > 9 ? parseInt(theTime) : '0' + parseInt(theTime);
    let result = h + m + ':' + s
    return result;
},

xAudioStop: function () {
    let that = this
    xBackMusic.pause()
},
// 手动打卡
punchClock:function(){
    let that =this;
    wx.showModal({
      title:'提示',
      content:'你已经自行完成了练习吗？',
      success (res) {
        if (res.confirm) {
          that.xToadd()
        }
      }
    })
  },
  // 新增记录
  xToadd:function(){
    let that =this;
    wx.showLoading({
      title: '保存中',
    })
    // if( that.data.count<5){
      let _dataObj = {
        treatment_item_id: that.data.treatment_item_id,
        week:that.data.week
      }
      wx.cloud.callFunction({
        name: 'audio_video_practice',
        data: {
          action: "add_practice_punching",
          dataObj: _dataObj
        }
      }).then(res => {
          wx.hideLoading()
          that.setData({
            count:that.data.count+1
          })
          that.xChildReload()
      })
    // }
  },
  xInit:function(){
    let that =this;
    let _dataObj = {
      week: that.data.week,
      treatment_item_id: that.data.treatment_item_id
    }
    wx.cloud.callFunction({
      name: 'audio_video_practice',
      data: {
        action: "get_all_audio_video_list",
        dataObj: _dataObj
      }
    }).then(res => {
      var dates =new Date()
      let data = res.result
      for(let index in data){
        for(let i in data[index].data){
          data[index].data[i].countdown= data[index].data[i].playback_duration
          if(index==0 && i==0){
            that.setData({
              count:data[index].data[i].practice_punching_count
            })
          }
        }
      }
      that.setData({
        action_list:data
      })
    })
    that.xToPracticeStatus()
  },
  // 动作详情
  xToInfo:function(e){
      let that =this;
      let action_id = e.currentTarget.dataset.action_id
      let name =e.currentTarget.dataset.name
      wx.navigateTo({
        url: '/subtool/pages/action/details/index?week='+that.data.week+'&action_id='+ action_id+'&treatment_item_id='+that.data.treatment_item_id+'&type='+that.data.type+'&name='+name,
      })
  },
  
  xToPracticeStatus:function(){
    let that =this;
    wx.cloud.callFunction({
      name: 'practice_help',
      data: {
        action: "get_practice_help_status",
        dataObj: {
          num:8 //3正念8放松
        }
      }
    }).then(res => {
      for(let index in res.result){
        if(res.result[index]._id==1){
          that.setData({
            PracticeStatus:res.result[index].status
          })
        }
      }
    })
  },
  xTosetM:function(){
    let that=this
    wx.setStorageSync(this.data.treatment_item_id, this.data.treatment_item_id)
    let _dataObj = {
      num:8,//练习任务类型数值
      type:1,//1:练习说明
    }
    wx.cloud.callFunction({
      name: 'practice_help',
      data: {
        action: "get_practice_help",
        dataObj: _dataObj
      }
    }).then(res => {
      res.result[0].content=text.text(res.result[0].content)
      this.setData({
        showtips:!this.data.showtips,
        practice_help:res.result[0]
      })
    })
      
  },
  xToNext:function(e){
    let that = this
    let id= e.currentTarget.dataset.id
    for(let index in that.data.action_list){
      for(let i in that.data.action_list[index].data){
        if(that.data.action_list[index].data[i]._id == that.data.current){
          that.setData({
            [`action_list[${index}].data[${i}].play`]:false
          })
          wx.getBackgroundAudioManager().stop()
        }
      }
    }
    wx.navigateTo({
      url: '/subtool/pages/productother/detail/index?id='+id+'&week='+that.data.week+'&treatment_item_id='+that.data.treatment_item_id,
    })
  },
  // xToTips:function(){
  //   wx.showModal({
  //     title: "提示",
  //     content: "此项任务今天已完成，请明天继续",
  //     showCancel: false,
  //     confirmText:'好的'
  //   })
  // },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.getBackgroundAudioManager().stop()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})